#include <iostream>
#include <vector>
#include <memory>

/**
 * @class Listener
 * @brief A listener class that can listen to events.
 * 
 * This class is derived from std::enable_shared_from_this to allow
 * listeners to provide a shared_ptr to themselves when registering
 * for events, without creating a new shared_ptr manually.
 */
class Listener : public std::enable_shared_from_this<Listener> {
public:

    void onEvent() {
        std::cout << "Event received!" << std::endl;
    }
};


class EventGenerator {
public:
    /**
     * @brief Register a listener for events.
     * 
     * @param listener A shared_ptr to the Listener to register.
     */
    void registerListener(std::shared_ptr<Listener> listener) {
        listeners.push_back(listener->weak_from_this());
    }

    /**
     * @brief Notify all registered listeners of an event.
     */
    void notifyListeners() {
        // 遍历所有注册的监听器
        for (auto weakListener : listeners) {
            // 尝试从 weak_ptr 获取 shared_ptr
            auto listener = weakListener.lock();
            // 检查返回的 shared_ptr 是否为空，确保监听器仍存在
            if (listener) {
                listener->onEvent();  // 安全调用监听器的事件处理函数
            } else {
                // 可以在这里处理监听器已销毁的情况，例如从列表中移除
                std::cout << "Listener has been destroyed and removed." << std::endl;
                // 移除逻辑代码（此处略）
            }
        }
    }

private:
    std::vector<std::weak_ptr<Listener>> listeners; ///< List of weak pointers to registered listeners.
};

int main() {
    auto eventGenerator = std::make_shared<EventGenerator>();
    auto listener1 = std::make_shared<Listener>();
    auto listener2 = std::make_shared<Listener>();

    eventGenerator->registerListener(listener1);
    eventGenerator->registerListener(listener2);

    // Simulate an event


    eventGenerator->notifyListeners();

    // Output will be:
    // Event received!
    // Event received!
    
    return 0;
}